// http.ts
import http from '@ohos.net.http';
import prompt from '@ohos.prompt';
import { ApiResponse } from './types'; // 确保类型导入正确

const BASE_URL = 'http://172.30.0.1:5000/api';

export class HttpClient { // 改为常规类导出
  private httpRequest: http.HttpRequest;

  constructor() {
    this.httpRequest = http.createHttp();
  }

  async post<T extends ApiResponse>(url: string, data: object): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.httpRequest.request(
        `${BASE_URL}${url}`,
        {
          method: http.RequestMethod.POST,
          header: { 'Content-Type': 'application/json' },
          extraData: JSON.stringify(data)
        },
        (err, response) => {
          if (err) {
            prompt.showToast({ message: '网络错误', duration: 2000 });
            reject(err);
            return;
          }

          try {
            const result: T = JSON.parse(response.result.toString());
            if (response.responseCode === 200 && result.success) {
              resolve(result);
            } else {
              prompt.showToast({ message: result.message || '请求失败', duration: 2000 });
              reject(result);
            }
          } catch (e) {
            prompt.showToast({ message: '数据解析失败', duration: 2000 });
            reject(e);
          }
        }
      );
    });
  }
}

const httpClient = new HttpClient();
export default httpClient;